const chalk = require('chalk')
const { stat } = require('fs')
const { resolve } = require('path')
const { searchComs } = require('./buildUtil')
const { root } = require('./util')
const { packWebpack } = require('./buildWebpack')

/**
 * 构建组件
 * @param { import('webpack-chain') } config 
 */
async function build(config) {
  await loadPackConfig(config)
}

async function loadPackConfig(buildConfig) {
  const configPath = resolve(root, 'jm.coms.config.js')

  const config = await new Promise((resolve, reject) => {
    stat(configPath, (err) => {
      if(err) {
        // 默认读取全部
        resolve({
          coms: [],
          subdir: ''
        })
      } else {
        try{
          resolve(require(configPath))
        }catch(e) {
          console.warn(chalk.warn('组件打包配置jm.coms.config.js解析失败', e))

          reject(e)
        }
      }
    })
  })

  let searchPath = resolve(root, 'packages')

  if(config.subdir) {
    searchPath = resolve(searchPath, config.subdir)
  }

  let coms = []

  const allComs = await searchComs(searchPath)

  if(config.coms && config.coms.length > 0) {
    // 过滤只需要打包的组件及其版本
    const allMap = allComs.reduce((map, item)=> {
      map.set(`${item.name}@${item.version}`, item)

      return map
    },new Map())

    config.coms.forEach(config=> {
      const com = allMap.get(`${config.name}@${config.version}`)

      if(com) {
        coms.push(com)
      }
    })
  } else {
    coms = allComs
  }

  await pack(coms, buildConfig)
}

/**
 * 打包
 */
async function pack(coms=[], buildConfig) {
  if(coms.length === 0) {
    console.log(chalk.yellow('无组件打包!'))
    return
  }

  return packWebpack(coms, buildConfig)
}

module.exports = {
  build
}
